package org.budo.support.web.realip;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.budo.support.lang.util.StringUtil;
import org.budo.support.mvcs.Mvcs;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Slf4j
@Getter
@Setter
public class RealIpFilter implements Filter {
    private String[] remoteAddrHeaderNames = Mvcs._REMOTE_ADDR_HEADER_NAMES;

    public void init(FilterConfig filterConfig) throws ServletException {
        String names = filterConfig.getInitParameter("remote-addr-header-names");
        if (!StringUtil.isEmpty(names)) {
            this.setRemoteAddrHeaderNames(StringUtil.split(names, ","));
        }

        log.info("#39 init, this=" + this + ", names=" + names + ", filterConfig=" + filterConfig);
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String[] remoteAddrHeaderNames = this.getRemoteAddrHeaderNames();
        RealIpRequestWrapper requestWrapper = new RealIpRequestWrapper(request, remoteAddrHeaderNames);
        chain.doFilter(requestWrapper, response);
    }

    public void destroy() {
        log.info("#47 destroy, this=" + this);
    }
}